from ._global import EPSILON
import math

class Vector:
    def __init__(self,lst):
        self._values = list(lst)
    
    def __repr__(self):
        return "Vector({})".format(self._values)

    def __str__(self):
        return "({})".format(", ".join(str(e) for e in self._values))

    def __len__(self):
        #返回向量长度
        return len(self._values)

    def __getitem__(self,index):
        return self._values[index]

    def __iter__(self):
        return self._values.__iter__()

    def __add__(self,another):
        assert len(self) == len(another) , \
        "Error in adding. Length of vecotors must be same."

        return Vector([a+b for a,b in zip(self,another)])

    def __sub__(self,another):
        assert len(self) == len(another) , \
        "Error in subtracting. Length of vecotors must be same."

        return Vector([a-b for a,b in zip(self,another)])

    def dot(self,another):
        '''点乘'''
        assert len(self) == len(another) , \
        "Error in dot product. Length of vecotors must be same."

        return sum([a*b for a,b in zip(self,another)])

    def __mul__(self,k):
        return Vector([a*k for a in self])

    def __rmul__(self,k):
        return self*k

    def __pos__(self):
        return self*1
    
    def __neg__(self):
        return self*-1

    def __truediv__(self,k):
        '''返回的数量除法'''
        return (1/k) * self

    @classmethod
    def zero(cls,dim):
        # return cls([0 for a in range(0,dim)])
        return cls([0]*dim)

    def norm(self):
        return math.sqrt(sum(e**2 for e in self))

    def normalize(self):
        # 浮点数精度存在误差
        if  self.norm() < EPSILON:
            raise ZeroDivisionError("norm is zero!")
        
        return Vector(self._values)/self.norm()

    def underlying_list(self):
        return self._values[:]